#import "HomePageDetailImageItemCell.h"
#import "HomePageDetailFooterView.h"
#import "XHPageControl.h"

@interface HomePageDetailImageItemCell ()<UIScrollViewDelegate,XHPageControlDelegate,HomePageDetailFooterViewDelegate>

//@property (nonatomic,strong)XHPageControl *pageControl;

@property (nonatomic,strong)HomePageDetailFooterView *footerView;
@property (nonatomic,strong)UIScrollView *imageScrollView;
@property (nonatomic,strong)NSMutableArray *scrollViewArray;

@property (nonatomic,strong)HomePageItemModel *currentModel;

@property (nonatomic,strong)NSMutableArray *errorArray;
@property (nonatomic,strong)NSMutableArray *lbArray;

@end

@implementation HomePageDetailImageItemCell


- (NSMutableArray *)scrollViewArray{
    if (!_scrollViewArray) {
        _scrollViewArray = [NSMutableArray array];
    }
    return _scrollViewArray;
}
- (NSMutableArray *)errorArray{
    if (!_errorArray) {
        _errorArray = [NSMutableArray array];
    }
    return _errorArray;
}
- (NSMutableArray *)lbArray{
    if (!_lbArray) {
        _lbArray = [NSMutableArray array];
    }
    return _lbArray;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setUI];
    }
    return self;
}
- (void)setUI{
 
    
    self.backgroundColor = [UIColor blackColor];
    self.imageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,kScreenW,kScreenH)];
    self.imageScrollView.backgroundColor = [UIColor clearColor];
    self.imageScrollView.scrollEnabled =YES;
    self.imageScrollView.pagingEnabled =YES;
    self.imageScrollView.delegate =self;
    self.imageScrollView.showsVerticalScrollIndicator = NO;
    self.imageScrollView.showsHorizontalScrollIndicator = NO;
    self.imageScrollView.contentSize =CGSizeMake(9*kScreenW,kScreenH);
    
    
    for (int i =0; i < 9; i++){

        UIScrollView *s = [[UIScrollView alloc]initWithFrame:CGRectMake(kScreenW*i,0,kScreenW, kScreenH)];
        s.backgroundColor = [UIColor clearColor];
        s.contentSize =CGSizeMake(kScreenW,kScreenH);
        s.delegate =self;
        s.showsHorizontalScrollIndicator = NO;
        s.showsVerticalScrollIndicator = NO;
        s.minimumZoomScale = 1;
        s.maximumZoomScale = 3;
        
        [s setZoomScale:1.0];
          
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,kScreenW, kScreenH)];
        imageview.userInteractionEnabled =YES;
        imageview.tag = i+1;
        imageview.contentMode = UIViewContentModeScaleAspectFit;
        imageview.layer.masksToBounds = YES;
        imageview.hidden = YES;
        imageview.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(coverMethod)];
        [imageview addGestureRecognizer:tap];
        [s addSubview:imageview];
        
        UIImageView *errorImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_error_img_tag"]];
        errorImgView.tag = i;
        errorImgView.hidden = YES;
        errorImgView.cl_centerX = self.imageScrollView.cl_centerX;
        errorImgView.cl_y = kScreenH/2 - 64;
        
        UILabel *lb = [[UILabel alloc]init];
        lb.text = @"加载失败，点击屏幕重试";
        lb.textColor = [UIColor whiteColor];
        lb.textAlignment = NSTextAlignmentCenter;
        lb.font = font(12);
        lb.hidden = YES;
        lb.frame = CGRectMake(0, CGRectGetMaxY(errorImgView.frame) + 16, kScreenW, 16);
        
        
        errorImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *refreshTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(refreshImgView:)];
        [errorImgView addGestureRecognizer:refreshTap];
        
        [s addSubview:errorImgView];
        [s addSubview:lb];

        [self.imageScrollView addSubview:s];
        [self.scrollViewArray addObject:imageview];
        [self.errorArray addObject:errorImgView];
        [self.lbArray addObject:lb];
         
     }
    [self.contentView addSubview:self.imageScrollView];
    

    __weak typeof(self)weakSelf = self;
    self.footerView = [[HomePageDetailFooterView alloc]initWithCompleteBlock:^(XHFooterType type) {
        if (type == XHFOOTERLIKE) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageItemLikeWithCurrentModel:)]) {
                [weakSelf.delegate imageItemLikeWithCurrentModel:weakSelf.currentModel];
            }
        }
        if (type == XHFOOTERDISS) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageItemDissWithCurrentModel:)]) {
                [weakSelf.delegate imageItemDissWithCurrentModel:weakSelf.currentModel];
            }
        }
        if (type == XHFOOTERFOLLOW) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageItemFollowWithCurrentModel:)]) {
                [weakSelf.delegate imageItemFollowWithCurrentModel:weakSelf.currentModel];
            }
        }
        if (type == XHFOOTERYUSER) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageItemUserInfoWithCurrentModel:)]) {
                [weakSelf.delegate imageItemUserInfoWithCurrentModel:weakSelf.currentModel];
            }
        }
        if (type == XHFOOTERCOMMENT) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageItemCommentWithCurrentModel:)]) {
                [weakSelf.delegate imageItemCommentWithCurrentModel:weakSelf.currentModel];
            }
        }
        if (type == XHFOOTERTOPIC) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageItemTopicListWithCurrentModel:)]) {
                [weakSelf.delegate imageItemTopicListWithCurrentModel:weakSelf.currentModel.tag];
            }
        }
    }];
   
    [self.footerView showInView:self.contentView delegate:self];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showMenuViewPress:)];
    [self.imageScrollView addGestureRecognizer:longPress];
    
}

- (void)showMenuViewPress:(UIGestureRecognizer *)gestureRecognizer{

    
    if (self.errorArray.count < self.currentModel.currentIndex) {
        return;
    }
    UIImageView *errorImgView = self.errorArray[self.currentModel.currentIndex];
    if (!errorImgView.hidden) {
        return;
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(imageItemLongPressToolView)]) {
            [self.delegate imageItemLongPressToolView];
        }
    }
}
- (void)refreshImgView:(UIGestureRecognizer *)gestureRecognizer{
    UIView *v = gestureRecognizer.view;
    v.hidden = YES;

    UILabel *lb = self.lbArray[v.tag];
    lb.hidden = YES;
    
    UIImageView *currentImgView = self.scrollViewArray[v.tag];
    [currentImgView sd_setImageWithURL:[NSURL URLWithString:self.currentModel.urls[v.tag]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (error != nil) {
            UIImageView *errorImgView = self.errorArray[v.tag];
            errorImgView.hidden = NO;
            
            UILabel *lb = self.lbArray[v.tag];
            lb.hidden = NO;
        }
    }];
}

- (void)scrollViewEnable:(BOOL)isEnable{
    if (self.delegate && [self.delegate respondsToSelector:@selector(imageItemScrollViewEnabale:)]) {
        [self.delegate imageItemScrollViewEnabale:isEnable];
    }
}

- (void)setItemModel:(HomePageItemModel *)itemModel indexPath:(NSIndexPath *)indexPath{
    
    self.currentModel = itemModel;
    [self.footerView setItemModel:itemModel animate:NO];
    [self.scrollViewArray enumerateObjectsUsingBlock:^(__kindof UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.hidden = YES;
        if (idx < itemModel.urls.count) {
            obj.hidden = NO;
            [obj sd_setImageWithURL:[NSURL URLWithString:itemModel.urls[idx]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (error != nil) {
                    UIImageView *errorImgView = self.errorArray[idx];
                    errorImgView.hidden = NO;
                    
                    UILabel *lb = self.lbArray[idx];
                    lb.hidden = NO;
                }
            }];
        }
    }];
    
    self.imageScrollView.contentSize = CGSizeMake(kScreenW * itemModel.urls.count, 0);

    [self.imageScrollView setContentOffset:CGPointMake(kScreenW * itemModel.currentIndex, 0) animated:NO];
    

}

#pragma mark - ScrollView delegate
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
   
    if (self.errorArray.count == 0) {
        return nil;
    }
    
    UIImageView *errorImgView = self.errorArray[self.currentModel.currentIndex];

    if (!errorImgView.isHidden) {
        return nil;
    }
    
    
    for (UIView *v in scrollView.subviews){
       return v;
    }
    return nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(interfaceOrientation ==UIInterfaceOrientationPortrait||interfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown)
    {
       return YES;
    }
    return NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    
    if (scrollView ==self.imageScrollView){
        
        NSInteger index = scrollView.contentOffset.x/kScreenW;
        self.currentModel.currentIndex = index;
        
        CGFloat x = scrollView.contentOffset.x;
        if (x==-kScreenW){
            
        }else{
            for (UIScrollView *s in scrollView.subviews){
                if ([s isKindOfClass:[UIScrollView class]]){
                    [s setZoomScale:1.0]; //scrollView每滑动一次将要出现的图片较正常时候图片的倍数（将要出现的图片显示的倍数）
                }
            }
        }
    }
    
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
   
    if (scrollView == self.imageScrollView) {
        NSInteger index = scrollView.contentOffset.x/kScreenW;
        
        if (scrollView.contentOffset.x <= 0) {
            [WHToast showMessage:@"已是第一张" duration:2 finishHandler:nil];
            return;
        }
        
        if (index == self.currentModel.urls.count - 1) {
            [WHToast showMessage:@"没有更多了" duration:2 finishHandler:nil];
            return;
        }
        

    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.imageScrollView){
        NSInteger index = scrollView.contentOffset.x/kScreenW;
        self.currentModel.currentIndex = index;
        if (self.delegate && [self.delegate respondsToSelector:@selector(imageItemSelectAtIndex:)]) {
            [self.delegate imageItemSelectAtIndex:self.currentModel.currentIndex];
        }
        
    }
}

+ (instancetype)cellWithTableView:(UITableView *)tableView{
    NSString *ID = @"HomePageDetailImageItemCell";
    HomePageDetailImageItemCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[HomePageDetailImageItemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}


- (void)coverMethod{
   self.currentModel.showFooterTool = !self.currentModel.showFooterTool;
   if (self.currentModel.showFooterTool) {
       [self.footerView show];
   }else{
       [self.footerView hide];
   }
   if (self.delegate && [self.delegate respondsToSelector:@selector(imageItemShowHideToolView)]) {
       [self.delegate imageItemShowHideToolView];
   }
}


@end
